/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 * <p>
 * https://www.renren.io
 * <p>
 * 版权所有，侵权必究！
 */

package com.songlanyun.modules.user.controller;

import com.alibaba.fastjson.JSONObject;
import com.songlanyun.common.utils.DateUtil;
import com.songlanyun.common.utils.R;

import com.songlanyun.common.utils.RedisKeys;
import com.songlanyun.common.utils.TokenGenerator;
import com.songlanyun.modules.rabbitmq.DelayedConstant;
import com.songlanyun.modules.rabbitmq.service.SendMsgService;
import com.songlanyun.modules.user.entity.SysUserEntity;
import com.songlanyun.modules.user.form.SysLoginForm;
import com.songlanyun.modules.user.service.SysCaptchaService;
import com.songlanyun.modules.user.service.SysUserService;
import com.songlanyun.modules.user.service.SysUserTokenService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 登录相关
 *
 * @author Mark sunlightcs@gmail.com
 */
@RestController
@Slf4j
public class SysLoginController extends AbstractController {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysUserTokenService sysUserTokenService;
    @Autowired
    private SysCaptchaService sysCaptchaService;

    @Resource
    RedisTemplate<Object, Object> redisTemplate;
    //12小时后过期
//    private final static int EXPIRE = 3600 * 12;

    @Value("${token.expiretime}")
    private int EXPIRE;


    /**
     * 验证码
     */
    @GetMapping("captcha.jpg")
    public void captcha(HttpServletResponse response, String uuid) throws IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        //System.out.println("server------>8081");
        //System.out.println("server------>8085");
        //获取图片验证码
        BufferedImage image = sysCaptchaService.getCaptcha(uuid);

        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
        IOUtils.closeQuietly(out);

    }

    /**
     * 登录
     */
    @PostMapping("/sys/login")
    public Map<String, Object> login(@RequestBody SysLoginForm form, @RequestParam(value = "need-code",required = false,defaultValue = "") String need) {

//        if (StringUtils.isBlank(need) ) {
//            // 检验验证码
//            boolean captcha = sysCaptchaService.validate(form.getUuid(), form.getCaptcha());
//            if (!captcha) {
//                return R.error("验证码不正确");
//            }
//        }

        //用户信息
//        SysUserEntity user = sysUserService.queryByUserName(form.getUsername());
        //wc 2020/12/16 用户名、手机号都可以登录
        SysUserEntity user = sysUserService.queryByUserNameAndMobile(form.getUsername());

        //账号不存在、密码错误
        if (user == null || !user.getPassword().equals(new Sha256Hash(form.getPassword(), user.getSalt()).toHex())) {
            return R.error("账号或密码不正确");
        }

        //账号锁定
        if (user.getStatus() == 0) {
            return R.error("账号已被锁定,请联系管理员");
        }

        //生成token，并保存到数据库  -- 修改为不用保存数据库
//        String token = sysUserTokenService.createToken(user.getUserId());
        String token = TokenGenerator.generateValue();
        //---ww end 登陆后将其数据权限 写入redis 中，供 dataInterceptor 来读取时判断权限  ---//
        redisTemplate.opsForValue().set(RedisKeys.getTokenConfigKey(token), user.getUserId().toString(), EXPIRE, TimeUnit.SECONDS);

        R r = R.ok().put("token", token).put("expire", EXPIRE);
        return r;
    }

    /**
     * 退出
     */
    @PostMapping("/sys/logout")
    public R logout() {
        sysUserTokenService.logout(getUserId());
        return R.ok();
    }

}
